﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CpuSimulator.Instructions
{
    /// <summary>
    ///LB(Load Byte) 将rs1中的值加上立即数作为地址，读取该地址中的字节值写入rd
    /// _________________________________________________________________________________________________________________________________________________
    /// |_________________立即数12位________________________|_________rs1,5位______|_Func3______|_________rd,5位______|_____OPCODE 7位____________|
    /// | 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 | 15 | 14 | 13 | 12 | 11 | 10 | 09 | 08 | 07 | 06 | 05 | 04 | 03 | 02 | 01 | 00 |
    /// |                         imm[11:0]                                        |       rs1                     |    000          |        rd                      |            0000011                     |
    /// </summary>
    public class LB : Instruction
    {
        public override void Execute(Cpu cpuinfo)
        {
            int address = cpuinfo.Registers[this.Rs1].Value + this.Immediate;
            Device device = new Device(0);
            int deviceStart = 0;
            foreach (var item in cpuinfo.AddressMap)
            {
                if (address >= item.Key.start && address < item.Key.end)
                {
                    device = item.Value;
                    deviceStart = address - item.Key.start;
                    break;
                }
            }
            if (device != null)
            {
                var newVal = (int)((sbyte)device[deviceStart]);
                cpuinfo.Registers[this.Rd].SetValue(newVal);
                cpuinfo.InvodeRegisterChange(this.Rd, newVal.ToString("X8"));
            }
        }
    }
}
